<template>
  <div class="ad-management">
    <!-- 操作栏：按钮 + 搜索 -->
    <div class="operation-bar">
      <div class="button-group">
        <el-button type="primary" @click="openAddDialog">添加广告位</el-button>
      </div>
      <div class="search-group">
        <el-input
          v-model="searchForm.keyword"
          placeholder="请输入广告位名称、广告编号"
          style="width: 240px;"
          @keyup.enter.native="searchAdvertis"
        />
        <el-button type="primary" icon="el-icon-search" @click="searchAdvertis">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
    </div>

    <!-- 广告位表格 -->
    <el-table 
      :data="tableData" 
      border 
      style="width: 100%; margin-bottom: 20px;"
      v-loading="loading"
    >
      <el-table-column prop="advertisingCode" label="广告位编号" width="120" />
      <el-table-column prop="advertisingName" label="广告位名称" width="120" />
      <el-table-column prop="advertisingStatus" label="广告位状态" width="100">
        <template #default="{row}">
          <el-tag :type="getStatusTagType(row.advertisingStatus)">
            {{ getStatusText(row.advertisingStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="communityName" label="小区" width="120" />
      <el-table-column prop="advertisingPosition" label="广告位位置" width="120" />
      <el-table-column prop="advertisingSize" label="广告位大小" width="100" />
      <el-table-column prop="advertisingPrice" label="广告位价格" width="120">
        <template #default="{row}">
          {{ row.advertisingPrice }}元
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="{row}">
          <el-button type="text" size="small" @click="addPricing(row)">添加收费标准</el-button>
          <el-button type="text" size="small" @click="openEditDialog(row)">编辑</el-button>
          <el-button type="text" size="small" @click="confirmDelete(row)" style="color: #F56C6C">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrap">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="prev, pager, next, jumper, sizes, total"
        :total="total"
      />
    </div>

    <!-- 添加/编辑广告位弹窗 -->
    <el-dialog
      :title="dialog.title"
      :visible.sync="dialog.visible"
      width="50%"
      @close="resetForm"
    >
      <el-form ref="adForm" :model="currentAdvertis" label-width="120px">
        <el-form-item label="广告位编号" prop="advertisingCode">
          <el-input v-model="currentAdvertis.advertisingCode" placeholder="自动生成" disabled />
        </el-form-item>
        <el-form-item label="广告位名称" prop="advertisingName" required>
          <el-input v-model="currentAdvertis.advertisingName" placeholder="请输入广告位名称" />
        </el-form-item>
        <el-form-item label="所属小区" prop="communityId" required>
          <el-select 
            v-model="currentAdvertis.communityId" 
            placeholder="请选择小区"
            filterable
            clearable
            @change="handleCommunityChange"
          >
            <el-option
              v-for="item in communityOptions"
              :key="item.communityId"
              :label="item.communityName"
              :value="item.communityId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="广告位状态" prop="advertisingStatus" required>
          <el-select v-model="currentAdvertis.advertisingStatus" placeholder="请选择状态">
            <el-option label="空闲" :value="0" />
            <el-option label="已出租" :value="1" />
            <el-option label="自用" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="广告位位置" prop="advertisingPosition" required>
          <el-input v-model="currentAdvertis.advertisingPosition" placeholder="请输入广告位位置" />
        </el-form-item>
        <el-form-item label="广告位大小" prop="advertisingSize" required>
          <el-input v-model="currentAdvertis.advertisingSize" placeholder="如：2m2">
            <template #append>m²</template>
          </el-input>
        </el-form-item>
        <el-form-item label="广告位价格" prop="advertisingPrice" required>
          <el-input v-model="currentAdvertis.advertisingPrice" placeholder="请输入广告位价格">
            <template #append>元</template>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit">确定</el-button>
      </span>
    </el-dialog>

    <!-- 收费标准弹窗 -->
    <el-dialog
    title="收费标准设置"
    :visible.sync="chargeStandardDialogVisible"
    width="400px"
  >
    <el-form :model="chargeStandardForm" label-width="100px">
      <el-form-item label="收费标准">
        <el-select 
          v-model="chargeStandardForm.pricingId" 
          placeholder="请选择收费标准"
          @change="handlePricingChange"
        >
          <el-option 
            v-for="item in pricingList" 
            :key="item.pricingId"
            :label="item.pricingName" 
            :value="item.pricingId"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="chargeStandardDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveChargeStandard">确定</el-button>
    </div>
  </el-dialog>
  </div>
</template>

<script>


export default {
  name: 'AdManagement',
  data() {
    return {
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      tableData: [],
      communityOptions: [],
      searchForm: {
        keyword: ''
      },
      dialog: {
        visible: false,
        title: '',
        isEdit: false
      },
      feeDialog: {
        visible: false,
        currentAd: null
      },
      currentAdvertis: {
        advertisingId: '',
        advertisingCode: '',
        advertisingName: '',
        advertisingStatus: 0,
        communityId: '',
        communityName: '',
        advertisingPosition: '',
        advertisingSize: '',
        feeStandardCount: 0,
        advertisingPrice: 0
      },
      feeStandardList: [],
      // 收费标准设置对话框
      chargeStandardDialogVisible: false,
      chargeStandardForm: {
        pricingId: '',
        pricingName: '',
        advertisingId: '', // 添加车位ID
        communityId: '',
      },
      pricingList: [], // 存储所有收费标准
      currentParkingSpace: null // 当前操作的车位
    }
  },
  mounted() {
    this.getAdvertisList();
    this.getCommunityOptions();
  },
  methods: {

    // 获取所有的收费标准
    getAllPricing() {
      this.$axios.get('http://192.168.214.129:8080/pricing/getpricebycommId', {
        params: {
          commId: this.chargeStandardForm.communityId,
        }
      }).then(resp => {
        if (resp.data.code === 200) {
          this.pricingList = resp.data.data || [];
        }
      }).catch(error => {
        console.error('获取收费标准失败:', error);
        this.$message.error('获取收费标准失败');
      });
    },
    // 添加收费标准
    addPricing(row) {
      console.log(row);
      this.currentParkingSpace = row; // 保存当前车位信息
      this.chargeStandardDialogVisible = true;
      this.chargeStandardForm.communityId = row.communityId; // 设置小区ID
      this.chargeStandardForm.advertisingId = row.advertisingId; // 设置广告位ID
      this.getAllPricing();
    },
    // 收费标准选择变化
    handlePricingChange(pricingId) {
      const selectedPricing = this.pricingList.find(item => item.pricingId === pricingId);
      if (selectedPricing) {
        this.chargeStandardForm.pricingName = selectedPricing.pricingName;
      }
    },
    // 保存收费标准
    saveChargeStandard() {
      if (!this.chargeStandardForm.pricingId) {
        this.$message.warning('请选择收费标准');
        return;
      }
      const params = {
        advertisingId: this.chargeStandardForm.advertisingId,
        pricingId: this.chargeStandardForm.pricingId
      };
      console.log(params);
      this.$axios.put('http://192.168.214.129:8080/advertising/bangAdvertis', params)
        .then(response => {
          if (response.data.code === 200) {
            this.$message.success('收费标准设置成功');
            this.chargeStandardDialogVisible = false;
            // 刷新车位列表
            this.getAdvertisList();
          } else {
            this.$message.error(response.data.message || '设置失败');
          }
        })
        .catch(error => {
          console.error('设置失败:', error);
          this.$message.error('设置失败');
        });
    },

    // 获取小区选项
    async getCommunityOptions() {
      try {
        const response = await this.$axios.get('http://192.168.214.129:8080/community/selcomm');
        if (response.data.code === 200) {
          this.communityOptions = response.data.data;
        }
      } catch (error) {
        console.error('获取小区列表失败:', error);
        this.$message.error('获取小区列表失败');
      }
    },

    // 处理小区选择变化
    handleCommunityChange(value) {
      const selected = this.communityOptions.find(item => item.communityId === value);
      if (selected) {
        this.currentAdvertis.communityName = selected.communityName;
      } else {
        this.currentAdvertis.communityName = '';
      }
    },

    // 状态文本转换
    getStatusText(status) {
      const statusMap = {
        0: '空闲',
        1: '已出租',
        2: '自用'
      };
      return statusMap[status] || '未知';
    },

    // 状态标签类型
    getStatusTagType(status) {
      const typeMap = {
        0: 'info',
        1: 'success',
        2: 'warning'
      };
      return typeMap[status] || 'info';
    },

    // 获取广告位列表
    async getAdvertisList() {
      this.loading = true;
      try {
        const response = await this.$axios.post('http://192.168.214.129:8080/advertising/all', {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchForm.keyword
        });
        
        if (response.data.code === 200) {
          this.tableData = response.data.data.records;
          this.total = response.data.data.total;
        } else {
          this.$message.error(response.data.message || '获取广告位列表失败');
        }
      } catch (error) {
        console.error('获取广告位列表失败:', error);
        this.$message.error('获取广告位列表失败');
      } finally {
        this.loading = false;
      }
    },

    //获取收费标准列表
    async getFeeStandardList() {
      this.$axios.post('http://192.168.214.129:8080/pricing/list',{
        page:1,
        size:100,
      }).then(resp=>{
        console.log(resp);
        if(resp.data.code === 200){
          this.feeStandardList = resp.data.data;
        }
      })
    },

    // 搜索广告位
    searchAdvertis() {
      this.currentPage = 1;
      this.getAdvertisList();
    },

    // 重置搜索
    resetSearch() {
      this.searchForm.keyword = '';
      this.currentPage = 1;
      this.getAdvertisList();
    },

    // 打开添加对话框
    openAddDialog() {
      this.dialog.title = '添加广告位';
      this.dialog.isEdit = false;
      this.dialog.visible = true;
    },

    // 打开编辑对话框
    openEditDialog(row) {
      this.dialog.title = '编辑广告位';
      this.dialog.isEdit = true;
      this.currentAdvertis = { 
        ...row,
        communityId: row.communityId || '',
        communityName: row.communityName || ''
      };
      this.dialog.visible = true;
    },

    // 确认提交表单
    async confirmSubmit() {
      try {
        let response;
        if (this.dialog.isEdit) {
          response = await this.$axios.post('http://192.168.214.129:8080/advertising/editAdvertis', this.currentAdvertis);
        } else {
          response = await this.$axios.post('http://192.168.214.129:8080/advertising/addAdver', this.currentAdvertis);
        }
        
        if (response.data.code === 200) {
          this.$message.success(this.dialog.isEdit ? '编辑成功' : '添加成功');
          this.dialog.visible = false;
          this.getAdvertisList();
        } else {
          this.$message.error(response.data.message || '操作失败');
        }
      } catch (error) {
        console.error('操作失败:', error);
        this.$message.error('操作失败');
      }
    },

    // 查看详情
    showDetail(row) {
      this.$router.push(`http://192.168.214.129:8080/advertising/detail/${row.advertisingId}`);
    },

    // 确认删除
    async confirmDelete(row) {
      try {
        await this.$confirm(`确定删除广告位 "${row.advertisingName}" 吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        const response = await this.$axios.delete('http://192.168.214.129:8080/advertising/delAdvertis', {
          params: { advertisingId: row.advertisingId }
        });
        
        if (response.data.code === 200) {
          this.$message.success('删除成功');
          this.getAdvertisList();
        } else {
          this.$message.error(response.data.message || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error);
          this.$message.error('删除失败');
        }
      }
    },

    // 分页相关方法
    handleSizeChange(val) {
      this.pageSize = val;
      this.getAdvertisList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getAdvertisList();
    },

    // 重置表单
    resetForm() {
      this.$refs.adForm?.resetFields();
      this.currentAdvertis = {
        advertisingCode: '',
        advertisingName: '',
        advertisingStatus: 0,
        communityId: '',
        communityName: '',
        advertisingPosition: '',
        advertisingSize: '',
        feeStandardCount: 0,
        advertisingPrice: ''
      };
    }
  }
}
</script>

<style scoped>
.ad-management {
  padding: 20px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.button-group {
  display: flex;
}

.search-group {
  display: flex;
  align-items: center;
}

.search-group .el-input {
  margin-right: 8px;
}

.pagination-wrap {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
